package org.example.completed.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.example.completed.domain.Post;
import org.example.completed.model.dto.PostAndAvatarDTO;
import org.example.completed.model.vo.ResultVO;
import org.example.completed.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 帖子表 PostController
 *
 * @since 2025-04-15
 */
@RestController
@RequestMapping("/post")
public class PostController {


    @Autowired
    private PostService postService;

    /**
     * 获取所有帖子
     * @return
     */
    @GetMapping
    public ResultVO<List<Post>> getAllPosts() {
        List<Post> posts = postService.list();
        return ResultVO.ok(posts);
    }

    /**
     * 添加帖子
     * @param post
     * @return
     */
    @PostMapping
    public ResultVO<?> addPost(@RequestBody Post post) {
        boolean success = postService.addPost(post);
        return success ? ResultVO.ok("发送成功") : ResultVO.fail("发送失败");
    }

    /**
     * 根据userId获取对应img和post
     * @return
     */
    @GetMapping("/getPostsByUserId")
    public ResultVO<PostAndAvatarDTO> getPostsByUsernameWithAvatar(@RequestParam String userId) {
        PostAndAvatarDTO postAndAvatarDTO = postService.getPostsByUserId(userId);
        return ResultVO.ok(postAndAvatarDTO);
    }

    /**
     * 根据id返回对应帖子
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultVO<Post> getPostById(@PathVariable String id) {
        Post post = postService.getById(id);
        return post != null ? ResultVO.ok(post) : ResultVO.fail("帖子不存在");
    }

    /**
     * 编辑对应id的帖子和图片
     * @param id 帖子ID
     * @param imageUrl 帖子图片URL
     * @param content 帖子内容
     * @return 操作结果
     */
    @PostMapping("/edit/{id}")
    public ResultVO<?> updatePost(@PathVariable String id,
                                     @RequestParam String imageUrl,
                                     @RequestParam String content) {
        Post post = new Post();
        post.setImageUrl(imageUrl);
        post.setContent(content);
        UpdateWrapper<Post> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        boolean success = postService.update(post, updateWrapper);
        return success ? ResultVO.ok("更新成功") : ResultVO.fail("更新失败");
    }

    /**
     * 根据id删除帖子
     * @param id
     * @return
     */
    @PostMapping("/delete/{id}")
    public ResultVO<?> deletePost(@PathVariable String id) {
        boolean success = postService.removeById(id);
        return success ? ResultVO.ok("删除成功") : ResultVO.fail("删除失败");
    }
}

